﻿using System;
using Newtonsoft.Json;
using ZilLion.Service.Core.Ioc;
using ZilLion.Service.Core.Snowflake;
using ZilLion.Service.Core.WebSocket;
using ZilLion.Service.Core.WebSocket.Interface;
using ZilLion.Service.TaskPlatform.Domain.Entity;
using ZilLion.Service.TaskPlatform.Domain.Respository.Interface;
using static ZilLion.Service.Core.Ioc.IocContainer;

namespace ZilLion.Service.TaskPlatform.Domain.TaskCommand
{
    public class TaskCommandHelper
    {
        public static void CreateTaskCommand(string nodeId,
            string taskid, EnumTaskCommandName commandName, IWebSocketHandler webSocketHandler = null)
        {
            var taskCommandRespository = Resolve<ITaskCommandRespository>();
            var taskConmmandEntity = new TaskConmmandEntity
            {
                CommandId = SnowflakeIdCreater.Instance().GetNextId().ToString(),
                CommandUpdateTime = DateTime.Now,
                Commandname = commandName.ToString(),
                Commandstate = (int) EnumTaskCommandState.None,
                NodeId = nodeId,
                Taskid = taskid
            };
            taskCommandRespository.SaveTaskConmmandEntity(taskConmmandEntity);

          

            webSocketHandler?.SendMessageToAllAsync(
                new SocketMessage
                {
                    MessageId = SnowflakeIdCreater.Instance().GetNextId().ToString(),
                    Data = JsonConvert.SerializeObject(taskConmmandEntity),
                    MessageType = commandName.ToString()
                });
        }


        public static void ReStartTask(string nodeId,
            string taskid)
        {
            CreateTaskCommand(nodeId, taskid, EnumTaskCommandName.StopTask);
            CreateTaskCommand(nodeId, taskid, EnumTaskCommandName.StartTask);
        }
    }
}